//
//  BLBuyVipController.m
//  Byelone
//
//  Created by Qi Liu on 2021/2/28.
//

#import "BLBuyVipController.h"
#import "YQInAppPurchaseTool.h"
#import "BLVipPriceCell.h"

@interface BLVipModel : NSObject
@property(nonatomic,strong)NSDictionary * userVipVo;
@property(nonatomic,strong)NSArray * openInfoList;
@property(nonatomic,strong)NSArray * vipRights;
@end
@implementation BLVipModel
@end



@interface BLBuyVipController ()<YQInAppPurchaseToolDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UIScrollView *baseSrollview;
@property (weak, nonatomic) IBOutlet UIImageView *iconImage;
@property (weak, nonatomic) IBOutlet UIImageView *vipImage;//是否为vip
@property (nonatomic,assign) BOOL isVip;
@property (weak, nonatomic) IBOutlet UILabel *nickName;
@property (weak, nonatomic) IBOutlet UIButton *openVip;//开通|续费按钮

@property (weak, nonatomic) IBOutlet UILabel *topLabel;
@property (weak, nonatomic) IBOutlet UILabel *bottomLable;

//购买按钮
//@property (weak, nonatomic) IBOutlet UIButton *leftBuyBtn;
//@property (weak, nonatomic) IBOutlet UIButton *midBuyBtn;
//@property (weak, nonatomic) IBOutlet UIButton *rightBuyBtn;


@property (weak, nonatomic) IBOutlet UILabel *leftLabel;
@property (weak, nonatomic) IBOutlet UILabel *midLabel;
@property (weak, nonatomic) IBOutlet UILabel *rightLabel;


@property(nonatomic,copy) NSDictionary * vipInfoDic;
@property(nonatomic,strong) BLVipModel * vipModel;
@property (weak, nonatomic) IBOutlet UICollectionView *priceView;
@property (nonatomic,strong) NSMutableArray *productArray;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *priceViewW;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *priceviewViewH;



@end

@implementation BLBuyVipController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"开通VIP";
    
    self.iconImage.layer.cornerRadius = 25;
    self.iconImage.layer.masksToBounds = YES;
    self.baseSrollview.showsVerticalScrollIndicator = NO;
    self.baseSrollview.showsHorizontalScrollIndicator = NO;
    self.baseSrollview.bounces = NO;
    [self loadNetData];
    
    
    //获取单例
    YQInAppPurchaseTool *IAPTool = [YQInAppPurchaseTool defaultTool];
    IAPTool.delegate = self;
    //购买后，向苹果服务器验证一下购买结果。默认为YES。不建议关闭
    //IAPTool.CheckAfterPay = NO;
    //向苹果询问哪些商品能够购买
    [IAPTool requestProductsWithProductArray:@[@"com.new.Byelone30",
                                               @"com.new.Byelone90",
                                               @"com.new.Byelone350"
    ]];
    
    [self collectionConfig];
    
    
}


-(void)loadNetData{
    
    [BLHttpTool getHttpRequest:BL_GC_VIP_INFO param:BL_EMPTYDIC finish:^(NSURLSessionDataTask * _Nonnull data, NSDictionary * _Nonnull obj) {
        
        //     NSDictionary * vipDic =  @{@"userVipVo":@{@"vip":@"0",
        //                         @"endTime":@"2021-7-5"
        //        },
        //          @"openInfoList":@[@{@"vipOpenType":@"1",
        //                              @"vipOpenPrice":@"3"},
        //                            @{@"vipOpenType":@"2",
        //                              @"vipOpenPrice":@"12"},
        //                            @{@"vipOpenType":@"3",
        //                              @"vipOpenPrice":@"35"},
        //
        //          ],
        //          @"vipRights":@[@{@"vipRight":@"1",
        //                           @"vipRightsName":@"广场无限删选"},
        //                         @{@"vipRight":@"2",
        //                           @"vipRightsName":@"赠送珍珠/贝壳"},
        //                         @{@"vipRight":@"3",
        //                           @"vipRightsName":@"查看最近访客"},]
        //        };
        //
        
        
        BLVipModel * model = [BLVipModel mj_objectWithKeyValues:[NSDictionary dictionaryWithDictionary:[obj objectForKey:@"content"]]];
        //        BLVipModel * model = [BLVipModel mj_objectWithKeyValues:vipDic];
        self.vipModel = model;
        self.vipModel = model;
        [self finishData];
    } failedBlock:^(id  _Nonnull data, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}

-(void)finishData{
    [self.iconImage sd_setImageWithURL:[NSURL URLWithString:[BLUserManager shareUser].userInfo.picture]];
    self.nickName.text = [BLUserManager shareUser].userInfo.nickName;
    
    if ([[_vipModel.userVipVo objectForKey:@"vip"] integerValue] ==0) {
        self.vipImage.hidden = YES;
        [self.openVip setTitle:@"立即开通" forState:UIControlStateNormal];
    }else{
        self.topLabel.text = @"欢迎您,尊贵的VIP会员";
        [self.openVip setTitle:@"立即续费" forState:UIControlStateNormal];
        self.bottomLable.text = [NSString stringWithFormat:@"有效期至%@",[_vipModel.userVipVo objectForKey:@"endTime"]];
    }
    
//    NSString * left = [NSString stringWithFormat:@"%@元",[ [_vipModel.openInfoList objectAtIndex:0] objectForKey:@"vipOpenPrice"]];
//    [self.leftBuyBtn setTitle:left forState:UIControlStateNormal];
//    NSString * mid = [NSString stringWithFormat:@"%@元",[ [_vipModel.openInfoList objectAtIndex:0] objectForKey:@"vipOpenPrice"]];
//    [self.midBuyBtn setTitle:mid forState:UIControlStateNormal];
//    NSString * right = [NSString stringWithFormat:@"%@元",[ [_vipModel.openInfoList objectAtIndex:0] objectForKey:@"vipOpenPrice"]];
//    [self.rightBuyBtn setTitle:right forState:UIControlStateNormal];
//
//    self.leftLabel.text = [[_vipModel.vipRights objectAtIndex:0] objectForKey:@"vipRightsName"];
//    self.midLabel.text = [[_vipModel.vipRights objectAtIndex:1] objectForKey:@"vipRightsName"];
//    self.rightLabel.text = [[_vipModel.vipRights objectAtIndex:2] objectForKey:@"vipRightsName"];
}



- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)vipType:(UIButton *)sender {
    
    NSInteger vipType = [[[_vipModel.openInfoList objectAtIndex:sender.tag] objectForKey:@"vipOpenType"] integerValue];
    
    NSDictionary * dic = @{@"vipOpenType":@(vipType),
                           @"payChannel":@(2)
    };
    
    [BLHttpTool postWithPath:BL_GC_VIP_BUYVIP params:dic successBlock:^(NSDictionary * _Nonnull obj) {
        
    } failedBlock:^(NSURLSessionDataTask * _Nonnull data, NSError * _Nonnull error) {
        
    }];
    
}

- (IBAction)buyVip:(UIButton *)sender {
    
}

- (IBAction)siftNum:(UIButton *)sender {
    //筛选
    switch (sender.tag) {
        case 0:
            
            break;
        case 1:
            
            break;
        case 2:
            
            break;
            
        default:
            break;
    }
}

#pragma mark --------YQInAppPurchaseToolDelegate
//IAP工具已获得可购买的商品
-(void)IAPToolGotProducts:(NSMutableArray *)products {
    NSLog(@"GotProducts:%@",products);
    //    for (SKProduct *product in products){
    //        NSLog(@"localizedDescription:%@\nlocalizedTitle:%@\nprice:%@\npriceLocale:%@\nproductID:%@",
    //              product.localizedDescription,
    //              product.localizedTitle,
    //              product.price,
    //              product.priceLocale,
    //              product.productIdentifier);
    //        NSLog(@"--------------------------");
    //    }
    
    
    
//    [products sortedArrayUsingComparator:^NSComparisonResult(SKProduct  * obj1, SKProduct * obj2) {
//        //升序，key表示比较的关键字
//        if (obj1.price < obj2.price) {
//            return NSOrderedAscending;
//        }else{
//            return NSOrderedDescending;
//        }
//        
//    }];
//
//    
//
//    
//    self.productArray = products;
//    
//    dispatch_async(dispatch_get_main_queue(), ^{
//        
//    });
//    
    
    NSLog(@"成功获取到可购买的商品");
    
}
//支付失败/取消
-(void)IAPToolCanceldWithProductID:(NSString *)productID {
    NSLog(@"canceld:%@",productID);
    //    [SVProgressHUD showInfoWithStatus:@"购买失败"];
}
//支付成功了，并开始向苹果服务器进行验证（若CheckAfterPay为NO，则不会经过此步骤）
-(void)IAPToolBeginCheckingdWithProductID:(NSString *)productID {
    NSLog(@"BeginChecking:%@",productID);
    
    //    [SVProgressHUD showWithStatus:@"购买成功，正在验证购买"];
}
//商品被重复验证了
-(void)IAPToolCheckRedundantWithProductID:(NSString *)productID {
    NSLog(@"CheckRedundant:%@",productID);
    
    //    [SVProgressHUD showInfoWithStatus:@"重复验证了"];
}

//最终验证结果
//商品完全购买成功且验证成功了。（若CheckAfterPay为NO，则会在购买成功后直接触发此方法）
-(void)IAPToolBoughtProductSuccessedWithProductID:(NSString *)productID
                                          andInfo:(NSDictionary *)infoDic {
    NSLog(@"BoughtSuccessed:%@",productID);
    NSLog(@"successedInfo:%@",infoDic);
    
    //    [SVProgressHUD showSuccessWithStatus:@"购买成功！(相关信息已打印)"];
}
//商品购买成功了，但向苹果服务器验证失败了
//2种可能：
//1，设备越狱了，使用了插件，在虚假购买。
//2，验证的时候网络突然中断了。（一般极少出现，因为购买的时候是需要网络的）
-(void)IAPToolCheckFailedWithProductID:(NSString *)productID
                               andInfo:(NSData *)infoData {
    NSLog(@"CheckFailed:%@",productID);
    
    //    [SVProgressHUD showErrorWithStatus:@"验证失败了"];
}
//恢复了已购买的商品（仅限永久有效商品）
-(void)IAPToolRestoredProductID:(NSString *)productID {
    NSLog(@"Restored:%@",productID);
    
    //    [SVProgressHUD showSuccessWithStatus:@"成功恢复了商品（已打印）"];
}
//内购系统错误了
-(void)IAPToolSysWrong {
    NSLog(@"SysWrong");
    //    [SVProgressHUD showErrorWithStatus:@"内购系统出错"];
}

//恢复已购买的商品
-(void)restoreProduct{
    
    //    [SVProgressHUD showWithStatus:@"正在恢复商品"];
    
    //直接调用
    [[YQInAppPurchaseTool defaultTool]restorePurchase];
}

//购买商品
-(void)BuyProduct:(SKProduct *)product{
    
    //    [SVProgressHUD showWithStatus:@"正在购买商品"];
    
    [[YQInAppPurchaseTool defaultTool]buyProduct:product.productIdentifier];
}




//MARK:collectionview
#define CELLID @"BLVipPriceCell"
#define CELLWH 80
-(void)collectionConfig{
    
    
    CGFloat scale = BL_WINDOW_WIDTH/375;
    _priceViewW.constant = 274 * scale;
    _priceviewViewH.constant = 90 * scale;
    
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumLineSpacing = 16.5 * scale;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(5 * scale, 0, 5 * scale, 0);
    flowLayout.itemSize =  CGSizeMake(CELLWH * scale, CELLWH * scale);
    [_priceView setCollectionViewLayout:flowLayout];
    _priceView.delegate = self;
    _priceView.dataSource = self;
    [_priceView registerNib:[UINib nibWithNibName:CELLID bundle:nil] forCellWithReuseIdentifier:CELLID];
    
    
    
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 3;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    BLVipPriceCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELLID forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:CELLID owner:nil options:nil]lastObject];
    }
    
    
    cell.priceSelect = cell.selected;
    return cell;
}

-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
       if( [collectionView cellForItemAtIndexPath:indexPath].selected){
           [self.priceView deselectItemAtIndexPath:indexPath animated:NO];
           [self collectionView:self.priceView didDeselectItemAtIndexPath:indexPath];
            return false;
       }
   
    return true;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
//    if (!_defaultSelected) {
//          ServerCell *cell = (ServerCell *)[collectionView cellForItemAtIndexPath:self.defaultIndex];
//          cell.baseImageView.image = [WUUtils imageWithColor:[UIColor whiteColor]];
//          cell.serverName.textColor = [UIColor blackColor];
//          _defaultSelected = YES;
//      }
    BLVipPriceCell *cell = (BLVipPriceCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.priceSelect = YES;
//
}


//取消选定
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
  
    BLVipPriceCell *cell = (BLVipPriceCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.priceSelect = NO;
}

@end
